package de.cbf.cam.dsa.exchange.ownxml;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

import de.cbf.cam.dsa.exchange.ownxml.composites.ChangeTextDialog;
import de.cbf.cam.dsa.model.Model;
import de.cbf.cam.dsa.model.entities.OneNPC;

/**
 * The activator class controls the plug-in life cycle
 */
public class Activator extends AbstractUIPlugin {

	// The plug-in ID
	public static final String PLUGIN_ID = "de.cbf.cam.dsa.exchange.ownXML";

	// The shared instance
	private static Activator plugin;
	
	/**
	 * The constructor
	 */
	public Activator() {
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	/**
	 * Returns the shared instance
	 *
	 * @return the shared instance
	 */
	public static Activator getDefault() {
		return plugin;
	}
	private class FunctionalityImport implements ActionListener{
		@Override
		public void actionPerformed(ActionEvent e) {	
			Shell shell = new Shell();
			shell.setText("Character importieren");
			FileDialog openDialog = new FileDialog(shell,SWT.OPEN);
			openDialog.setFilterExtensions(new String[]{"*.xml"});
			openDialog.setFilterNames(new String[]{"CharacterXML"});
			String fileName = openDialog.open();
			if(fileName != null){
				try {
					OneNPC character = XMLImporter.importCharacter(fileName);
					
					boolean addSucessfull = false;
					do{					//try to add once and try again, if fails
						addSucessfull = Model.getInstance().addPossibleCharacter(character);		
						if(! addSucessfull){ 
							// handle double character -> enter new name or cancel
							ChangeTextDialog dialog = new ChangeTextDialog(shell,SWT.APPLICATION_MODAL);
							dialog.setHeading("Vorhanden: "+character.getName());
							dialog.setText(character.getName());
							
							String newName = dialog.open();
							if(newName!=null){
								character.setName(newName);
							}else{
								//dialog was canceled or name not valid -> error -> no import
								break;
							}
						}
					}while(!addSucessfull);  				
					
				} catch (FileNotFoundException e1) {
					e1.printStackTrace();
				}
			}else{
				//handle dialog closed / error
			}
		}		
	}
}
